package cn.nawang.ebeim.server.service;

import cn.nawang.ebeim.server.constants.Config;
import cn.nawang.ebeim.server.entity.StorageCloud;
import cn.nawang.ebeim.server.entity.StorageServer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 负责与API服务器交互
 * Created by GanJc on 2015-12-28 16:46
 */
public class ApiService {

    private final static Logger LOG = LoggerFactory.getLogger(ApiService.class);

    private final static String API_URL = Config.API_URL + "/ebeim-api/api/token";

    // 获取云存储对象
    private final static String URL_GET_STORAGE_CLOUD_BY_NAME =
            API_URL + "/storage_cloud/find/storage_cloud_name";

    // 获取云存储服务器列表
    private final static String URL_SERVER_LIST =
            API_URL + "/storage_server/find/storage_cloud_id";

    private ApiService() {}

    private static ApiService apiService;

    public static ApiService getInstance() {
        if (apiService == null) {
            synchronized (ApiService.class) {
                if (apiService == null) {
                    apiService = new ApiService();
                }
            }
        }
        return apiService;
    }

    public String getZookeeperHosts() {
        if (Config.ZK_HOSTS == null) {
            StorageCloud storageCloud = getStorageCloudByName();
            List<StorageServer> servers = getStorageCloudServerList(storageCloud.getId());
            StringBuffer zkHostsBuffer = new StringBuffer();
            for (StorageServer server : servers) {
                if (server.getInternalHost() != null) {
                    zkHostsBuffer.append(server.getInternalHost() + ":" + server.getInternalPort() + ",");
                } else {
                    zkHostsBuffer.append(server.getHost() + ":" + server.getPort() + ",");
                }
            }
            Config.ZK_HOSTS = zkHostsBuffer.toString();
        }
        return Config.ZK_HOSTS;
    }

    private List<StorageServer> getStorageCloudServerList(String storageCloudId) {
        String[] arr = {"storageCloudId", storageCloudId, "token", "tokennawang"};
        HttpRequest request = HttpRequest.get(URL_SERVER_LIST, true, arr);
        LOG.info("request:" + request);
        String jsonText = request.body();
        LOG.info("response:" + jsonText);
        request.disconnect();
        JSONObject obj = JSONObject.parseObject(jsonText);
        return JSON.parseArray(obj.getString("list"), StorageServer.class);
    }

    private StorageCloud getStorageCloudByName() {
        String[] arr = {"name", Config.STORAGE_CLOUD_NAME, "token", "tokennawang"};
        HttpRequest request = HttpRequest.get(URL_GET_STORAGE_CLOUD_BY_NAME, true, arr);
        LOG.info("request:" + request);
        String jsonText = request.body();
        LOG.info("response:" + jsonText);
        request.disconnect();
        if (jsonText == null || "".equals(jsonText)) {
            throw new RuntimeException("getStorageCloudByName error,please check storageCloud on api server!");
        }
        JSONObject obj = JSONObject.parseObject(jsonText);
        String code = obj.get("code").toString();
        String objString = obj.getString("obj");
        if ("200".equals(code) && objString != null) {
            return JSON.parseObject(objString, StorageCloud.class);
        } else {
            throw new RuntimeException("getStorageCloudByName error,please check storageCloud on api server!");
        }
    }

}
